package cn.com.connext.scrm.service;

import cn.com.connext.scrm.domain.enumeration.AuditStatus;
import cn.com.connext.scrm.domain.enumeration.DeleteStatus;
import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.*;
import cn.com.connext.scrm.service.dto.*;
import cn.com.connext.scrm.service.mapper.ActivityMapper;
import cn.com.connext.scrm.service.mapper.AwardRecordMapper;
import cn.com.connext.scrm.service.mapper.GiftMapper;
import cn.com.connext.scrm.service.mapper.NoteMapper;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.vm.*;
import com.alibaba.fastjson.JSON;
import com.connext.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.time.ZonedDateTime;
import java.util.*;

/***
 *  created by wangzhan on 2018/01/24
 *
 *  小程序 活动管理
 */
@Service
@Transactional
public class ActivityService extends BaseService<Activity, String> {
    private final Logger log = LoggerFactory.getLogger(ActivityService.class);

    private final ActivityRepository activityRepository;

    @Autowired
    private AwardRecordRepository awardRecordRepository;
    @Autowired
    private AwardRecordMapper awardRecordMapper;

    @Autowired
    private NoteRepository noteRepository;

    @Autowired
    private NoteMapper noteMapper;

    @Autowired
    private GiftService giftService;

    @Autowired
    private PrizeGoodService prizeGoodService;

    @Autowired
    private GiftRepository giftRepository;

    @Autowired
    private GiftMapper giftMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private DrawActivityRepository drawActivityRepository;

    @Autowired
    private NewDrawActivityRepository newDrawActivityRepository;

    @Autowired
    private DrawActivityGoodRepository drawActivityGoodRepository;

    @Autowired
    private ActivityModuleConfigRepository amcRepository;

    @Autowired
    private ActivityModuleRepository amRepository;

    @Autowired
    private ActivityModuleConfigChildRepository amcchildRepository;

    public ActivityService(ActivityRepository activityRepository) {
        super(activityRepository);
        this.activityRepository = activityRepository;
    }

    /**
     * 获取当前正在进行的活动
     *
     * @return
     */
    public List<Activity> getCurrentActivities() {
        return activityRepository.getCurrentActivity();
    }

    /***
     * 获取待领取奖品记录
     * @return
     */
    public AwardRecordDTO getAwardRecordByUnionId(String unionId) {
        List<String> activityIds = activityRepository.getAwardStageActivities();
        if (activityIds != null && activityIds.size() > 0) {
            for (String activityId : activityIds) {
                List<AwardRecord> list = awardRecordRepository.getByUnionIdAndActivityIdAndStateFalseOrderByCreateTime(unionId, activityId);
                log.info("getAwardRecordByUnionId.list:{}", JSON.toJSONString(list));
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        AwardRecord awardRecord = list.get(i);
                        log.info("getAwardRecordByUnionId.awardRecord:{}", JSON.toJSONString(awardRecord));
                        if (awardRecord.getCloseTimes() < 2) {
                            AwardRecordDTO dto = awardRecordMapper.toDto(awardRecord);
                            if (StringUtils.isNotEmpty(dto.getGiftId())) {
                                Gift gift = giftRepository.findOne(dto.getGiftId());
                                GiftDTO giftDTO = giftMapper.toDto(gift);
                                dto.setGiftDTO(giftDTO);
                            }
                            return dto;
                        }
                    }
                }
            }
        }
        return null;
    }

    /***
     * 提交奖品寄送信息
     * @param id
     * @param expressAddress
     */
    public String submitExpressAddress(String id, String expressAddress, String expressMobile, String addressee) {
        AwardRecord awardRecord = awardRecordRepository.getOne(id);

        if (awardRecord.isState()) {
            return "奖品已领取";
        }
        awardRecord.setExpressAddress(expressAddress);
        awardRecord.setExpressMobile(expressMobile);
        awardRecord.setAddressee(addressee);
        awardRecord.setRegisterTime(ZonedDateTime.now());
        awardRecord.setState(true);
        awardRecordRepository.save(awardRecord);
        return "快递地址已提交";
    }

    public AwardRecord consumeCard(String unionId, String cardId) {
        log.info("进入方法:{},{}", unionId, cardId);
        List<AwardRecord> list = awardRecordRepository.findByUnionIdAndCardId(unionId, cardId);
        log.info("list:{}", list);
        if (list.size() > 0) {
            AwardRecord record = list.get(0);
            record.setState(true);
            record.setRegisterTime(ZonedDateTime.now());
            log.info("record:{}", JSON.toJSONString(record));
            awardRecordRepository.save(record);
            return record;
        } else {
            return null;
        }
    }

    public void closeCard(QueryIdVM vm) {
        AwardRecord record = awardRecordRepository.findOne(vm.getId());
        if (record != null) {
            record.setCloseTimes(record.getCloseTimes() + 1);
            awardRecordRepository.save(record);
        }
    }

    public Page<ActivityDTO> pageQuery(PageQueryVM vm) {
        Pageable pageable = new PageRequest(vm.getPage(), vm.getPageSize(), new Sort(Sort.Direction.DESC, "createTime"));
        Specification<Activity> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("isAnswer"), 0));//问答
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<Activity> page = activityRepository.findAll(specification, pageable);
        Page<ActivityDTO> dtoPage = page.map(activity -> activityMapper.toDto(activity));
        return dtoPage;
    }

    public Page<DrawActivityDTO> queryDrawList(QueryActivityVM vm) {
        Pageable pageable = new PageRequest(vm.getPage(), vm.getPageSize(), new Sort(Sort.Direction.DESC, "createTime"));
        Specification<DrawActivity> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.isNotEmpty(vm.getActivityId())) {
                list.add(criteriaBuilder.equal(root.get("id"), vm.getActivityId()));//问答
            }
            if (StringUtils.isNotEmpty(vm.getActivityName())) {
                list.add(criteriaBuilder.equal(root.get("activityName"), vm.getActivityName()));
            }
            if (StringUtils.isNotEmpty(vm.getActivityType())) {
                list.add(criteriaBuilder.equal(root.get("activityType"), vm.getActivityType()));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<DrawActivity> page = drawActivityRepository.findAll(specification, pageable);
        Page<DrawActivityDTO> dtoPage = page.map(activity -> this.toDrawActivityDTO(activity));
        return dtoPage;
    }

    private DrawActivityDTO toDrawActivityDTO(DrawActivity activity) {
        DrawActivityDTO dto = new DrawActivityDTO();
        BeanUtils.copyProperties(activity, dto);
        List<Integer> prizeGoodIds = new ArrayList<>();
        List<DrawActivityGood> drawActivityGoods = this.drawActivityGoodRepository.findByActivityId(activity.getId());
        drawActivityGoods.forEach(drawActivityGood -> {
            prizeGoodIds.add(drawActivityGood.getPrizeGoodId());
        });
        dto.setPrizeGoodIds(prizeGoodIds);
        return dto;
    }

    public ActivityDTO edit(ActivityVM vm) {
        Activity activity;
        if (StringUtils.isNotEmpty(vm.getId())) {
            activity = activityRepository.findOne(vm.getId());
        } else {
            activity = new Activity();
        }
        if (StringUtils.isNotEmpty(vm.getActivityName())) {
            activity.setActivityName(vm.getActivityName());
        }
        if (StringUtils.isNotEmpty(vm.getActivityPage())) {
            activity.setActivityPage(vm.getActivityPage());
        }
        if (StringUtils.isNotEmpty(vm.getContent())) {
            activity.setContent(vm.getContent());
        }
        if (StringUtils.isNotEmpty(vm.getImageUrl())) {
            activity.setImageUrl(vm.getImageUrl());
        }
        if (StringUtils.isNotEmpty(vm.getDescription())) {
            activity.setDescription(vm.getDescription());
        }
        if (vm.getStartTime() != null) {
            activity.setStartTime(vm.getStartTime());
        }
        if (vm.getEndTime() != null) {
            activity.setEndTime(vm.getEndTime());
        }
        if (vm.getDeadline() != null) {
            activity.setDeadline(vm.getDeadline());
        }
        activity.setIsAnswer(false);
        Activity activity1 = activityRepository.save(activity);
        return activityMapper.toDto(activity1);
    }

    public DrawActivityDTO editDraw(DrawActivityVM vm) {
        DrawActivity activity;
        if (StringUtils.isNotEmpty(vm.getId())) {
            activity = drawActivityRepository.findOne(vm.getId());
        } else {
            activity = new DrawActivity();
        }
        if(StringUtils.isNotEmpty(vm.getCampaignID())){
            activity.setCampaignID(vm.getCampaignID());
        }
        if(StringUtils.isNotEmpty(vm.getSource())){
            activity.setSource(vm.getSource());
        }
        if(StringUtils.isNotEmpty(vm.getSourceContent())){
            activity.setSourceContent(vm.getSourceContent());
        }
        if (StringUtils.isNoneEmpty(vm.getIsMultipath())) {
            activity.setIsMultipath(vm.getIsMultipath());
        }
        if (StringUtils.isNotEmpty(vm.getActivityName())) {
            activity.setActivityName(vm.getActivityName());
        }

        if (StringUtils.isNotEmpty(vm.getContent())) {
            activity.setContent(vm.getContent());
        }

        if (StringUtils.isNotEmpty(vm.getImageUrl())) {
            activity.setImageUrl(vm.getImageUrl());
        }

        if (null!=vm.getStartTime()) {
            activity.setStartTime(vm.getStartTime());
        }

        if (null!=vm.getEndTime()) {
            activity.setEndTime(vm.getEndTime());
        }

        if (null!=vm.getNeedPoint()) {
            activity.setNeedPoint(vm.getNeedPoint());
        }

        if (null!=vm.getJoinNumber()) {
            activity.setJoinNumber(vm.getJoinNumber());
        }

        if (StringUtils.isNotEmpty(vm.getButtonName())) {
            activity.setButtonName(vm.getButtonName());
        }

        if (StringUtils.isNotEmpty(vm.getButtonImg())) {
            activity.setButtonImg(vm.getButtonImg());
        }

        if (StringUtils.isNotEmpty(vm.getUrl())) {
            activity.setUrl(vm.getUrl());
        }
        if (StringUtils.isNotEmpty(vm.getActivityType())) {
            activity.setActivityType(vm.getActivityType());
        }
        if (null !=vm.getBackgroundColor()) {
            activity.setBackgroundColor(vm.getBackgroundColor());
        }
        if (null !=vm.getNotHavePrizeFlag()) {
            activity.setNotHavePrizeFlag(vm.getNotHavePrizeFlag());
        }
        if (null !=vm.getGoodId()) {
            activity.setGoodId(vm.getGoodId());
        }

        if (StringUtils.isNotBlank(vm.getHelpActivityName())) {
            activity.setHelpActivityName(vm.getHelpActivityName());
        }
        if (StringUtils.isNotBlank(vm.getWinMessageRemark())) {
            activity.setWinMessageRemark(vm.getWinMessageRemark());
        }
        if (StringUtils.isNotBlank(vm.getPrizeExpireMessageRemark())) {
            activity.setPrizeExpireMessageRemark(vm.getPrizeExpireMessageRemark());
        }
//        activity.setEnableFlag(vm.getEnableFlag());
        activity.setCreateTime(new Date());
        activity.setUpdateTime(new Date());
        activity.setType(1);
        activity.setCanDelete(1);
        //添加消息订阅功能
        activity.setIsMessage(vm.getIsMessage());
        activity.setPrizeExpireMessage(vm.getPrizeExpireMessage());
        activity.setWinMessage(vm.getWinMessage());
        DrawActivity activity1 = this.drawActivityRepository.saveAndFlush(activity);
        //添加或编辑活动子模块
        if (activity1 !=null) {

            //方法修改于20210810,修改内容为:对应新增功能多路径配置
//            List<NewDrawActivity> newactivity = null;
            NewDrawActivity newDrawActivity =null;
            List<NewDrawActivity> newactivity = newDrawActivityRepository.findByDrawActivityId(activity1.getId());
            if(newactivity == null || newactivity.size() == 0){

                    newDrawActivity = new NewDrawActivity();

                    newDrawActivity.setCreateTime(ZonedDateTime.now());

                    if(StringUtils.isNotEmpty(vm.getCampaignID())){
                        newDrawActivity.setCampaignID(vm.getCampaignID());
                    }
                    if(StringUtils.isNotEmpty(vm.getSource())){
                        newDrawActivity.setSource(vm.getSource());
                    }
                    if(StringUtils.isNotEmpty(vm.getActivityName())){
                        newDrawActivity.setSourceContent(vm.getActivityName());
                    }
                    newDrawActivity.setDrawActivityId(activity1.getId());
                    newDrawActivity.setPath(activity1.getId());

                    newDrawActivityRepository.saveAndFlush(newDrawActivity);
                }


            // 2021-5-24  新增活动 维护页面显示项 <来源内容> 赋值为活动名称  update cuijian start
//            if(StringUtils.isNotEmpty(vm.getSourceContent())){
//                newactivity.setSourceContent(vm.getSourceContent());
//            }

            // 2021-5-24  新增活动 维护页面显示项 <来源内容> 赋值为活动名称  update cuijian end


        }
        if (null != vm.getPrizeGoodIds()) {
            log.info("保存关系...");
            List<DrawActivityGood> activityGoods = this.drawActivityGoodRepository.findByActivityId(activity1.getId());
            if (activityGoods.size() > 0) {
                this.drawActivityGoodRepository.deleteInBatch(activityGoods);
            }
            for (Integer prizeGoodId : vm.getPrizeGoodIds()) {
                DrawActivityGood drawActivityGood = new DrawActivityGood();
                drawActivityGood.setActivityId(activity1.getId());
                drawActivityGood.setPrizeGoodId(prizeGoodId);
                drawActivityGood.setCreateTime(new Date());
                drawActivityGoodRepository.saveAndFlush(drawActivityGood);
            }
        }
        return toDrawActivityDTO(activity1);
    }

    public void deleteById(String id) {
        Activity activity = activityRepository.findOne(id);
        activity.setIsDelete(1);
        activity.setUpdateTime(new Date());
        activityRepository.save(activity);
    }

    public void deleteDrawById(String id) {
        DrawActivity activity = drawActivityRepository.findOne(id);
        if (activity != null) {
            List<DrawActivityGood> drawActivityGoods = this.drawActivityGoodRepository.findByActivityId(activity.getId());
            drawActivityGoodRepository.deleteInBatch(drawActivityGoods);
            drawActivityRepository.delete(activity);
        }
    }

    public void enable(String id) {
        Activity activity = activityRepository.findOne(id);
        if (activity == null) {
            throw new ServiceException(MyErrorCode.ERROR_DATA_ISNULL);
        }
        if (activity.isEnableFlag()) {
            activity.setEnableFlag(false);
        } else {
            activity.setEnableFlag(true);
        }
        activityRepository.save(activity);
    }

    public void drawEnable(String id) {
        DrawActivity activity = drawActivityRepository.findOne(id);
        if (activity == null) {
            throw new ServiceException(MyErrorCode.ERROR_DATA_ISNULL);
        }
        if (activity.isEnableFlag()) {
            activity.setEnableFlag(false);
        } else {
            activity.setEnableFlag(true);
        }
        drawActivityRepository.save(activity);
    }

    public ActivityDTO detail(String id) {
        Activity activity = activityRepository.findOne(id);
        return activityMapper.toDto(activity);
    }

    public DrawActivityDTO drawDetail(String id) {
        DrawActivity activity = drawActivityRepository.findOne(id);
        DrawActivityDTO activityDTO = toDrawActivityDTO(activity);
        /**
         * 详情显示组件名称及组件图片
         */
        List<ActivityModule> list = amRepository.findByActivityId(id);
        List<ActivityModuleConfigVM> returnList =new ArrayList<>();
        if(list !=null && list.size() >0){
            ActivityModuleConfigVM vm =null;
            for (ActivityModule config:list ) {
                if (config.getActivityModuleConfigId() != null) {
                    List<ActivityModuleConfigChild> activityChildList = amcchildRepository.findByActivityModuleConfigId(config.getActivityModuleConfigId());
                    ActivityModuleConfig con = amcRepository.findOne(config.getActivityModuleConfigId());
                    vm = new ActivityModuleConfigVM();
                    vm.setActivityId(id);
                    //20211013添加组件市场存在严重 防止手动删除组件信息
                    if(null!= con) {
                        vm.setId(con.getId());
                        vm.setComponentName(con.getComponentName());
                        vm.setType(con.getType());
                    }

                    if (activityChildList != null && activityChildList.size() > 0) {
                        if (con != null) {
                            if (con.getType() == 1) {
                                //轮播图
                                vm.setIsAutoLb(con.getIsAutoLb());
                                vm.setLbtList(activityChildList);
                                vm.setTitle("轮播图");
                            } else if (con.getType() == 2) {
                                //视频
                                vm.setVideoUrl(activityChildList.get(0).getUrl());
                                vm.setTitle("视频");
                                vm.setUrl(activityChildList.get(0).getUrl());
                                vm.setVideoImage(activityChildList.get(0).getVideoImage());
                            } else if (con.getType() == 3) {
                                //图片
                                vm.setImgUrl(activityChildList.get(0).getUrl());
                                vm.setTitle("图片");
                                vm.setUrl(activityChildList.get(0).getUrl());
                            }
                            returnList.add(vm);
                        }
                    }
                }
            }
        }
        activityDTO.setReturnList(returnList);

        //活动类型为领券时，查询出券奖品
        if ("2".equals(activity.getActivityType())) {
//            PrizeGood good = prizeGoodService.findById(activity.getGoodId());
            //优惠券奖品
            PrizeGood good = prizeGoodService.findByActivityIdAndType(id, 3);
            activityDTO.setPrizeGood(good);
        }
        return activityDTO;
    }

    public Page<NoteDTO> getNoteByActivityId(ActivityIdPageVM vm) {
        if (vm.getState() == null) {
            vm.setState(0);
        }
        Pageable pageable = new PageRequest(vm.getPage(), vm.getPageSize());
        List<Note> list = noteRepository.findByActivityIdAndAuditStatusAndDeleteStatusOrderByCreateTimeDesc(vm.getActivityId(), AuditStatus.AUDITED, DeleteStatus.ACTIVATED);
        List<NoteDTO> dtoList = new ArrayList<>();
        for (Note note : list) {
            NoteDTO dto = noteMapper.toDto(note);
            dtoList.add(dto);
        }
        log.info("dtoList:{}", JSON.toJSONString(dtoList.get(0)));
        if (vm.getState() == 1) {
            Collections.sort(dtoList, new Comparator<NoteDTO>() {
                @Override
                public int compare(NoteDTO o1, NoteDTO o2) {
                    if (o1.getTotalLikes() > o2.getTotalLikes()) {
                        return -1;
                    }
                    return 0;
                }
            });
        }
        Page page = new PageImpl(dtoList, pageable, dtoList.size());
        Page<NoteDTO> dtoPage = page;
        return dtoPage;
    }

    public Activity findActivityIdOne(String activityId){
        Activity byActivityId = activityRepository.findById(activityId);
        return byActivityId;
    }
}
